<template>
    <div class="store-home" :style="pageStyles" @click="detectClick">
        <!-- 1. Banner Section -->
        <div data-component="banner">
             <el-carousel :height="bannerHeight" indicator-position="none">
                <el-carousel-item v-for="(item, index) in config.banner.items" :key="index">
                    <img :src="item.imageUrl" alt="Banner" style="width: 100%; height: 100%; object-fit: cover;">
                </el-carousel-item>
            </el-carousel>
            <div class="banner-upload-container">
                <el-upload
                    v-for="(item, index) in config.banner.items"
                    :key="index"
                    :action="uploadUrl"
                    :headers="{ token: userInfo.token }"
                    :data="{ type: 2 }"
                    :show-file-list="false"
                    :on-success="(res, file, fileList) => handleBannerUploadSuccess(res, file, fileList, item.id)"
                    :before-upload="beforeExcelUpload"
                >
                    <img v-if="item.imageUrl" :src="item.imageUrl" class="editor-image" />
                    <i v-else class="el-icon-plus uploader-icon"></i>
                </el-upload>
            </div>
        </div>

        <!-- 2. Icon Navigation -->
        <div data-component="iconNav" class="icon-nav-section" :style="iconNavGridStyle">
            <div class="icon-item" v-for="(item, index) in config.iconNav.items" :key="item.id">
                <el-upload
                    :action="uploadUrl"
                    :headers="{ token: userInfo.token }"
                    :data="{ type: 2 }"
                    :show-file-list="false"
                    :on-success="(res, file, fileList) => handleIconUploadSuccess(res, file, fileList, item.id)"
                    :before-upload="beforeExcelUpload"
                >
                    <img v-if="item.imageUrl" :src="item.imageUrl" :alt="item.text" class="editor-image">
                    <i v-else class="el-icon-plus uploader-icon"></i>
                </el-upload>
                <el-input v-model="item.text" placeholder="图标文字" size="small"></el-input>
            </div>
        </div>

        <!-- 3. Product Recommendations -->
        <div data-component="products" class="product-section">
            <h3 class="section-title">商品推荐</h3>
            <div class="product-grid" :class="'layout-' + config.products.layout">
                <div class="product-card" v-for="product in config.products.items" :key="product.id">
                    <el-upload
                        :action="uploadUrl"
                        :headers="{ token: userInfo.token }"
                        :data="{ type: 2 }"
                        :show-file-list="false"
                        :on-success="(res, file, fileList) => handleProductUploadSuccess(res, file, fileList, product.id)"
                        :before-upload="beforeExcelUpload"
                    >
                        <img v-if="product.imageUrl" :src="product.imageUrl" :alt="product.name" class="editor-image">
                        <i v-else class="el-icon-plus uploader-icon"></i>
                    </el-upload>
                    <el-input v-model="product.text" placeholder="商品名称" size="small"></el-input>
                    <div class="product-footer">
                        <span class="product-price">💰 ???</span>
                        <i class="el-icon-shopping-cart-2"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            bannerHeight: '180px',
            uploadUrl: '/admin/upload/upload', // 上传接口地址
            userInfo: {
                token: localStorage.getItem('token') || ''
            },
            config: { // Default empty structure
                banner: { items: [] },
                iconNav: { items: [], itemsPerRow: 4 },
                products: { items: [], layout: 'grid' }
            },
            originalConfig: null // 新增：保存原始数据
        };
    },
    computed: {
        pageStyles() { return {}; },
        iconNavGridStyle() {
            return {
                gridTemplateColumns: `repeat(${this.config.iconNav.itemsPerRow}, 1fr)`
            };
        }
    },
    mounted() {
        window.addEventListener('message', this.handleMessage);
        this.fetchAdminList(); // 初始化数据
    },
    beforeDestroy() {
        window.removeEventListener('message', this.handleMessage);
    },
    methods: {
        handleMessage(event) {
            const { type, payload } = event.data;
            if (type === 'updateConfig') {
                this.config = payload;
            }
        },
        detectClick(event) {
            let target = event.target;
            while(target && target !== this.$el) {
                if(target.hasAttribute('data-component')) {
                    const componentName = target.getAttribute('data-component');
                    window.parent.postMessage({
                        type: 'focusComponent',
                        payload: componentName
                    }, '*');
                    return;
                }
                target = target.parentElement;
            }
        },
        fetchAdminList(params = {}) {
            this.$http.get('/admin/diy/getShopIndex').then(result => {
                if (result.code === 200) {
                    const data = result.data;
                    this.config.banner.items = (data.banner_index || []).map(item => ({
                        id: item.id,
                        name: item.name,
                        thumb: item.thumb,
                        imageUrl: item.thumb ? $appConfig.baseUrl + item.thumb : '',
                        text: item.name
                    }));
                    this.config.iconNav.items = (data.clas || []).map(item => ({
                        id: item.id,
                        name: item.name,
                        text: item.name,
                        icon: item.icon,
                        imageUrl: item.icon ? $appConfig.baseUrl + item.icon : '',
                        textColor: '#333333',
                        fontSize: 12
                    }));
                    this.config.products.items = (data.recommend_goods || []).map(item => ({
                        id: item.id,
                        name: item.title,
                        text: item.title,
                        f_thumb: item.f_thumb || item.thumb,
                        imageUrl: (item.f_thumb || item.thumb) ? $appConfig.baseUrl + (item.f_thumb || item.thumb) : '',
                        price: item.price
                    }));
                    this.originalConfig = JSON.parse(JSON.stringify(this.config));
                }
            });
        },
        handleBannerUploadSuccess(response, file, fileList, bannerId) {
            if (response.code === 200) {
                const idx = this.config.banner.items.findIndex(item => item.id === bannerId);
                if (idx !== -1) {
                    this.$set(this.config.banner.items, idx, {
                        ...this.config.banner.items[idx],
                        thumb: response.data[0],
                        imageUrl: $appConfig.baseUrl + response.data[0]
                    });
                }
                this.$message.success('文件上传成功');
            } else {
                this.$message.error(response.message || '上传失败');
            }
        },
        handleIconUploadSuccess(response, file, fileList, iconId) {
            if (response.code === 200) {
                const idx = this.config.iconNav.items.findIndex(item => item.id === iconId);
                if (idx !== -1) {
                    this.$set(this.config.iconNav.items, idx, {
                        ...this.config.iconNav.items[idx],
                        icon: response.data[0],
                        imageUrl: $appConfig.baseUrl + response.data[0]
                    });
                }
                this.$message.success('文件上传成功');
            } else {
                this.$message.error(response.message || '上传失败');
            }
        },
        handleProductUploadSuccess(response, file, fileList, productId) {
            if (response.code === 200) {
                const idx = this.config.products.items.findIndex(item => item.id === productId);
                if (idx !== -1) {
                    this.$set(this.config.products.items, idx, {
                        ...this.config.products.items[idx],
                        f_thumb: response.data[0],
                        imageUrl: $appConfig.baseUrl + response.data[0]
                    });
                }
                this.$message.success('文件上传成功');
            } else {
                this.$message.error(response.message || '上传失败');
            }
        },
        saveChanges() {
            // 只传有改动的项，没改的项不传
            const banners = this.config.banner.items
                .map((item, idx) => {
                    const old = (this.originalConfig && this.originalConfig.banner.items[idx]) || {};
                    if (item.thumb !== old.thumb) {
                        return { id: item.id, thumb: item.thumb };
                    }
                    return null;
                })
                .filter(Boolean);

            const icons = this.config.iconNav.items
                .map((item, idx) => {
                    const old = (this.originalConfig && this.originalConfig.iconNav.items[idx]) || {};
                    const changed = {};
                    if (item.icon !== old.icon) changed.icon = item.icon;
                    if (item.text !== old.text) changed.text = item.text;
                    if (Object.keys(changed).length) {
                        changed.id = item.id;
                        return changed;
                    }
                    return null;
                })
                .filter(Boolean);

            const products = this.config.products.items
                .map((item, idx) => {
                    const old = (this.originalConfig && this.originalConfig.products.items[idx]) || {};
                    const changed = {};
                    if (item.f_thumb !== old.f_thumb) changed.f_thumb = item.f_thumb;
                    if (item.text !== old.text) changed.text = item.text;
                    if (Object.keys(changed).length) {
                        changed.id = item.id;
                        return changed;
                    }
                    return null;
                })
                .filter(Boolean);

            this.$http.post('/admin/diy/edit', {
                change: {
                    ...(banners.length ? { banner: banners } : {}),
                    ...(icons.length ? { clas: icons } : {}),
                    ...(products.length ? { recommend_goods: products } : {})
                }
            }).then(res => {
                if (res.code === 200) {
                    this.$message.success('保存成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(res.message || '保存失败');
                }
            });
        },
        beforeExcelUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                this.$message.error('上传文件只能是图片格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                return false;
            }
            return true;
        }
    }
};
</script>

<style scoped lang="less">
.store-home { background-color: #f7f8fa; font-family: sans-serif; }

.banner-upload-container {
    display: flex;
    gap: 10px;
    padding: 10px;
    flex-wrap: wrap;
}

.icon-nav-section {
    display: grid; /* Use Grid for dynamic columns */
    background-color: #fff;
    padding: 10px 0;
    margin: 10px;
    border-radius: 8px;
    gap: 10px; /* space between icons */

    .icon-item {
        text-align: center;
        img {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            margin-bottom: 5px;
            cursor: pointer;
        }
        p { margin: 0; }
    }
}

.product-section {
    margin: 10px;
    padding: 15px;
    background-color: #fff;
    border-radius: 8px;

    .section-title { font-size: 16px; margin: 0 0 15px; text-align: left; }

    .product-grid.layout-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
    .product-grid.layout-list .product-card {
        display: flex;
        align-items: center;
        gap: 10px;
        & + .product-card { margin-top: 10px; }
        img { flex-shrink: 0; }
    }

    .product-card {
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;

        img {
            width: 100%;
            display: block;
            cursor: pointer;
        }
        .product-name { font-size: 14px; padding: 5px 10px; margin: 0; }
        .product-footer { display: flex; justify-content: space-between; align-items: center; padding: 5px 10px 10px; }
    }
}

.editor-image {
    width: 80px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
}

.uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
}

.el-upload {
    display: inline-block;
}
</style>
